﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json;
using System.Text;
using System.IO;
using Newtonsoft.Json.Converters;
using ServerPicture.Models;


namespace ServerPicture.Controllers
{
    public class CateController : ApiController
    {
        //chú ý...là tên biến của method pải đúng như trong router mapping vd: api/{controller}/{action}/{id}=>   GetAllProducts(id)

        //get all photo
        public IEnumerable<Cate> GetAllCate()
        {
            IList<Cate> photo = new List<Cate>();
            DatabaseDataContext db = new DatabaseDataContext();
            var list = from p in db.Categories where p.Enable==true orderby p.Cate_Name ascending
                       select new Models.Cate
                       {
                           Cate_ID = p.Cate_ID,
                           Cate_Date = string.Format("{0:dd/MM/yyyy}", p.Cate_Date),                    
                           Cate_Des=p.Cate_Description,
                           Cate_Name =p.Cate_Name ,
                           

                       };
            photo = list.ToList();
            if (photo == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            return photo;
        }

      

        /// <summary>
        /// Get list tag of id
        /// </summary>
        /// <param name="idphoto"></param>
        /// <returns></returns>
        [Route("api/cate/{id:int}")]
        [HttpGet]
        public List<Models.Tag> getlisttagofcate(int id)
        {
            List<Models.Tag> lsttag = new List<Models.Tag>();
            DatabaseDataContext db = new DatabaseDataContext();
            var r = (from p in db.TagCouples
                     where p.Photo.Cate_ID == id group p by new {tagid=p.TagID,tagname=p.Tag.Tag_Name} into g
                  select g).ToList();

            string cout = "";
            foreach (var i in r)
            {
                Models.Tag tag = new Models.Tag();
                tag.Tag_ID =Convert.ToInt32(i.Key.tagid);
                tag.Tag_Name = i.Key.tagname.ToString();
                lsttag.Add(tag);

            }
                 cout=r.Count().ToString();

                 return lsttag;
        }
    }
}
